package com.wyp.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wyp.pojo.Apartments;
import com.wyp.pojo.Examinees;
import com.wyp.service.impl.ApartmentsServiceImpl;
import com.wyp.service.impl.ExamineesServiceImpl;
import com.wyp.service.impl.ScoresServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class ExamineeManController {

    @Autowired
    private ExamineesServiceImpl examineesService;

    @Autowired
    private ApartmentsServiceImpl apartmentsService;

    @Autowired
    private ScoresServiceImpl scoresService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @GetMapping("/examinee_passupdate.html/{number}")
    public String tostupassupdate(
            @PathVariable("number") String number,
            Model model
    ) {
        Map<String, Object> examinees = examineesService.findByStuaccount(number);
        model.addAttribute("updatestu", examinees);
        return "admin/examinee/examinee_passupdate";
    }

    @PostMapping("/examinee_passupdate.html")
    public String stupassupdate(
            @RequestParam("registerNumber") String number,
            @RequestParam("registerPassword") String password,
            Model model
    ) {
        Map<String, Object> examinee = examineesService.findByStuaccount(number);
        Examinees examinees = new Examinees();
        examinees.setStuid((int) examinee.get("stuid"));
        examinees.setStuname((String) examinee.get("stuname"));
        examinees.setApartmentid((int) examinee.get("apartmentid"));
        examinees.setGender((Boolean) examinee.get("gender"));
        examinees.setStuaccount(number);
        examinees.setStupassword(encoder.encode(password));
        boolean info = examineesService.updateExaminees(examinees);
        return "redirect:/admin/examinee_update.html/" + number;

    }

    @GetMapping("/examinee_update.html/{number}")
    public String tostupdate(
            @PathVariable("number") String number,
            Model model
    ) {
        Map<String, Object> examinees = examineesService.findByStuaccount(number);
        List<Apartments> apartments = apartmentsService.qureyAllApartment();
        model.addAttribute("apartments", apartments);
        model.addAttribute("updatestu", examinees);
        return "admin/examinee/examinee_update";
    }

    @PostMapping("/examinee_update.html")
    public String stupdate(
            @RequestParam("registerUsername") String username,
            @RequestParam("registerApartment") int apartment,
            @RequestParam("registerGender") boolean gender,
            @RequestParam("registerNumber") String number,
            Model model
    ) {

        Map<String, Object> examinee = examineesService.findByStuaccount(number);
        Examinees examinees = new Examinees();
        examinees.setStuid((int) examinee.get("stuid"));
        examinees.setStuname(username);
        examinees.setApartmentid(apartment);
        examinees.setGender(gender);
        examinees.setStuaccount((String) examinee.get("stuaccount"));
        examinees.setStupassword((String) examinee.get("stupassword"));
        boolean info = examineesService.updateExaminees(examinees);
        return "redirect:/admin/examinee_manage.html";
    }

    @RequestMapping("/examinee_qurey.html")
    public String tostuqurey(Model model,
                             @Nullable @RequestParam(value = "qureyby") Integer qureyby,
                             @Nullable @RequestParam(value = "qureymessage") String qureymessage
//                           @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
//                           @RequestParam(value = "pageSize", defaultValue = "5") int pageSize
    ) throws UnsupportedEncodingException {
        if (qureymessage != null && !(qureymessage.equals(""))) {
            qureymessage = new String(qureymessage.getBytes("utf-8"), "iso-8859-1");
            return "redirect:/admin/examinee_qurey.html/" + qureyby + "/" + qureymessage;
        } else {
            return "redirect:/admin/examinee_manage.html";
        }
    }

    @RequestMapping("/examinee_qurey.html/{qureyby}/{qureymessage}")
    public String stuqurey(
            Model model,
            @PathVariable(value = "qureyby") Integer qureyby,
            @Nullable @PathVariable(value = "qureymessage") String qureymessage,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "4") int pageSize) {
        if (pageNum <= 0) {
            pageNum = 1;
        }
        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum, pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            if (qureymessage == null || qureymessage.equals("")) {
                List<Map<String, Object>> examineesList = examineesService.qureyAllExaminees();
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(examineesList, pageSize);
                model.addAttribute("pageInfo", pageInfo);
            }
            if ((qureyby == 1) && (qureymessage != null)) {
                List<Map<String, Object>> examineesList = examineesService.qureyExamineesByStuname(qureymessage);
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(examineesList, pageSize);
                model.addAttribute("pageInfo", pageInfo);
            }
            if ((qureyby == 0) && (qureymessage != null)) {
                List<Map<String, Object>> examineesList = examineesService.qureyExamineesByStuaccount(qureymessage);
                PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(examineesList, pageSize);
                model.addAttribute("pageInfo", pageInfo);
            }
        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        return "admin/examinee/examinee_manage";
    }

    @GetMapping("/examinee_add.html")
    public String tostuadd(Model model) {
        List<Apartments> apartments = apartmentsService.qureyAllApartment();
        model.addAttribute("apartments", apartments);
        return "admin/examinee/examinee_add";
    }

    @GetMapping("/examinee_delete.html/{id}")
    public String studelete(@PathVariable("id") int id) {
        List<Map<String, Object>> scores = scoresService.qureyScoresByStuid(id);
        for (Map<String, Object> score : scores) {
            scoresService.deleteScores((int) score.get("scoresid"));
        }
        examineesService.deleteExaminees(id);
        return "redirect:/admin/examinee_manage.html";
    }

    @RequestMapping("/examinee_manage.html")
    public String tologin(Model model,
                          @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "4") int pageSize) {
        if (pageNum <= 0) {
            pageNum = 1;
        }
        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum, pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            List<Map<String, Object>> examineesList = examineesService.qureyAllExaminees();
            //3.使用PageInfo包装查询后的结果,5是连续显示的条数,结果list类型是Page<E>
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(examineesList, pageSize);
            //4.使用model/map/modelandview等带回前端
            model.addAttribute("pageInfo", pageInfo);
        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        return "admin/examinee/examinee_manage";
    }


    @RequestMapping("/findRegisterUsername")
    @ResponseBody
    public Map<String, Object> findRegisterUsername(String username) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        boolean isExist;
        if (examineesService.findByStuaccount(username) != null) {
            isExist = true;
        } else {
            isExist = false;
        }
        resultMap.put("isExist", isExist);
        return resultMap;
    }


    @PostMapping("/examinee_add.html")
    public String stuadd(@RequestParam("registerUsername") String username,
                         @RequestParam("registerApartment") int apartment,
                         @RequestParam("registerGender") boolean gender,
                         @RequestParam("registerNumber") String number,
                         @RequestParam("registerPassword") String password,
                         Model model
    ) {
        Examinees examinees = new Examinees();
        examinees.setStuname(username);
        examinees.setApartmentid(apartment);
        examinees.setGender(gender);
        examinees.setStuaccount(number);
        examinees.setStupassword(encoder.encode(password));
        boolean info = examineesService.addExaminees(examinees);
        return "redirect:/admin/examinee_manage.html";
    }

}
